﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.Collections.Specialized;
using TracyGUI.Model;
using SharedLib.MessageFramework;
using SharedLib.MessageFramework.Messages;

namespace TracyGUI.ExceptionHandling
{
    [ConfigurationElementType(typeof(CustomHandlerData))]
    public class MessageExceptionHandler : IExceptionHandler
    {
        public MessageExceptionHandler(NameValueCollection data)
        {
        }

        /// <summary>
        /// Filter exceptions. IgnorableException will be just logged in console. ApplicationException will be shown to user.
        /// </summary>
        /// <param name="exception"></param>
        /// <param name="handlingInstanceId"></param>
        /// <returns></returns>
        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            bool ignoreFlag = false;
            if (exception is MessageException)
            {
                MessageException msgEx = exception as MessageException;
                IAppMessage msg = msgEx.AppMessage;
                if (msg != null)
                {
                    //Ignore web exception
                    if (msg.HandlerUID.Contains("GetXmlFromURLHandler") || msg.HandlerUID.Contains("GetDataFromURLHandler"))
                    {
                        ignoreFlag = true;
                    }else if (msg.HandlerUID.Contains("AssignMediaFileHandler"))
                    {
                        if (msgEx.InnerException.Message.Contains("Failed to download torrent file") ||
                            msgEx.InnerException is FormatException)
                        {
                            ignoreFlag = true;
                        }
                        
                    }
                    else if (msg.HandlerUID.Contains("StartDownloadHandler") && msgEx.InnerException.Message.StartsWith("Failed to download resource"))
                    {
                        ignoreFlag = true;
                    }
                }
            }

            if (ignoreFlag) return new IgnorableException();
            return new ApplicationException(Tracy.TracyFacade.Instance.LanguageManager.GetText("ErrorMessage_ApplicationException") ?? "Application Exception Occurred", exception);
        }
    }
}
